﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.IO;

namespace SL8.SL.Data.Helpers
{
    public static class MappingHelper
    {
        public static string GetMappingTableName(Type type)
        {
            object[] atts = type.GetCustomAttributes(typeof(Mapping.TableAttribute), false);

            if (atts.Length == 1)
            {
                return ((Mapping.TableAttribute)atts[0]).Name;
            }
            else
            {
                throw new Exception("找不到映射信息");
            }
        }

        public static string GetMappingDataSourceName(Type type)
        {
            object[] atts = type.GetCustomAttributes(typeof(Mapping.DataSourceAttribute), false);

            if (atts.Length == 1)
            {
                return ((Mapping.DataSourceAttribute)atts[0]).Name;
            }
            else
            {
                throw new Exception("找不到映射信息");
            }
        }

        public static IEnumerable<PropertyInfo> GetMappingColumns(Type type)
        {
            PropertyInfo[] propertyInfos = type.GetProperties();

            foreach (var item in propertyInfos)
            {
                object[] atts = item.GetCustomAttributes(typeof(Mapping.ColumnAttribute), false);

                if (atts.Length == 1)
                {
                    yield return item;
                }
            }
        }

        public static PropertyInfo GetKeyColumn(Type type)
        {
            PropertyInfo[] propertyInfos = type.GetProperties();

            PropertyInfo propertyInfo = null;
            foreach (var item in propertyInfos)
            {
                object[] atts = item.GetCustomAttributes(typeof(KeyAttribute), false);

                if (atts.Length == 1)
                {
                    if (propertyInfo == null)
                    {
                        propertyInfo = item;
                    }
                    else
                    {
                        throw new Exception("发现有多个主键");
                    }
                }
            }

            return propertyInfo;
        }

    }
}
